package com.fengplus.demo.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fengplus.demo.entity.CommonResult;
import com.fengplus.demo.handler.SentinelBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sentinel")
public class SentinelController {

    @GetMapping("/a")
    public CommonResult a(){
        return new CommonResult(200, null, "Sentinel A");
    }

    @GetMapping("/b")
    public String b(){
        try{
            Thread.sleep(2000);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "Sentinel B";
    }

    // 热点限流
    // 当访问地址带p1的QPS超过一定阀值限流
    // http://127.0.0.1:8302/sentinel/c?p1=a 限流
    // http://127.0.0.1:8302/sentinel/c?p1=a&p2=b 限流
    // http://127.0.0.1:8302/sentinel/c?p2=b 不限
    // 例外，设置p1=b，阀值200
    // http://127.0.0.1:8302/sentinel/c?p1=b 不限
    @GetMapping("/c")
    public String c(@RequestParam(value = "p1", required = false) String p1,
                    @RequestParam(value = "p2", required = false) String p2) {
        return "Sentinel C";
    }

    // 局部blockHandler
    @GetMapping("/d")
    @SentinelResource(value = "sentinelD", blockHandler = "dHandler")
    public CommonResult d(){
        return new CommonResult(200, null, "Sentinel D");
    }
    public CommonResult dHandler(BlockException exception){
        return new CommonResult<>(400, "Sentinel D Handler");
    }

    // 全局blockHandler
    @GetMapping("/e")
    @SentinelResource(value = "sentinelE", blockHandlerClass = SentinelBlockHandler.class, blockHandler = "handlerExceptionA")
    public CommonResult e(){
        return new CommonResult(200, null, "Sentinel E");
    }

    // 局部fallback
    @GetMapping("/f")
    @SentinelResource(value = "sentinelF", fallback = "fFallback")
    public CommonResult f(){
        int i = 10/0;
        return new CommonResult(200, null, "Sentinel F");
    }
    public CommonResult fFallback(Throwable e){
        return new CommonResult<>(400, "Sentinel F Fallback");
    }

    // 默认fallback
    @GetMapping("/g")
    @SentinelResource(value = "sentinelG", defaultFallback = "gFallback")
    public CommonResult g(){
        int i = 10/0;
        return new CommonResult(200, null, "Sentinel G");
    }

    public CommonResult gFallback(){
        return new CommonResult<>(400, "Sentinel G Default Fallback");
    }

}
